package it.univpm.diiga.semanticsearch.gestione;

import it.univpm.diiga.semanticsearch.configurazione.Configuration;

import java.io.File;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.security.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class Authentication {
	
	public boolean checkUserPassword(String username,String password){
		String localPath=Configuration.getLocalPath();
		boolean out=false;
		
		try{
		// Create a new instance of MessageDigest, using MD5. SHA and other
		// digest algorithms are also available.
		MessageDigest alg = MessageDigest.getInstance("MD5");

		// Reset the digest, in case it's been used already during this section of code
		// This probably isn't needed for pages of 210 simplicity
		alg.reset(); 

		// Calculate the md5 hash for the password. md5 operates on bytes, so give
		// MessageDigest the byte verison of the string
		alg.update(password.getBytes());

		// Create a byte array from the string digest
		byte[] digest = alg.digest();

		// Convert the hash from whatever format it's in, to hex format
		// which is the normal way to display and report md5 sums
		// This is done byte by byte, and put into a StringBuffer
		StringBuffer hashedpasswd = new StringBuffer();
		String hx;
		for (int i=0;i<digest.length;i++){
			hx =  Integer.toHexString(0xFF & digest[i]);
			//0x03 is equal to 0x3, but we need 0x03 for our md5sum
			if(hx.length() == 1){hx = "0" + hx;}
			hashedpasswd.append(hx);
		}

		// Print out the string hex version of the md5 hash
			String hash=hashedpasswd.toString();
		
		
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document=null;
			//try{
					document = db.parse(new File(localPath));
			   		
					Element rootEle = document.getDocumentElement(); //config
					

			//RECUPERO DATI ADMIN 
			NodeList admin = rootEle.getElementsByTagName("user");
			if (admin.getLength()==0){
				return false;
			}
	
			        
			
			for(int i = 0 ; i < admin.getLength();i++) {	
				 
				Element lista_ele = (Element)admin.item(i);
				
					
				NodeList user = lista_ele.getElementsByTagName("username");
			           if(user != null && user.getLength() > 0) {

			               Element ele = (Element)user.item(0);
			               if (ele.hasChildNodes()){ // if node exist
			               		if (ele.getFirstChild().getNodeValue().equals(username)){
			               			Element pass = (Element)lista_ele.getElementsByTagName("password").item(0);
			               			if (pass.getFirstChild().getNodeValue().equals(hash)){
			               				out= true;
			               				
			               			}else{
			               				out= false;
			               			}          				
			               			
			               		}else{
			               			//   da rimuovere  //
			               			//out= false;  -- gli out=false settati nei prox else
			               		}   //                non farebbero funzionare sicuro l'auth
			               			//                se nell'xml ci fosse piu di un user
			               			//                è sufficiente che all'inizio del metodo
			               		    //				  out è inizializzato a false
			               }else{
			            	   //out= false;
			               } 				
						}else{        	   
							//out= false;
						}
	           
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			return out;
		}
	}
	

}
